<template>
  <el-form label-width="100px" :model="skuInfo" ref="skuFormRef" :rules="skuRules">
    <el-form-item label="SPU名称">
      <span>{{ props.currentSpuInfo.spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input placeholder="SKU名称" v-model="skuInfo.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格(元)" prop="price">
      <el-input-number class="mx-4" v-model="skuInfo.price" style="width:100%;" :min="1" :max="10"
        controls-position="right" />
    </el-form-item>
    <el-form-item label="重量(千克)" prop="weight">
      <el-input-number style="width:100%" v-model="skuInfo.weight" class="mx-4" :min="1" :max="10"
        controls-position="right" />
    </el-form-item>
    <el-form-item label="规格描述" prop="skuDesc">
      <el-input type="textarea" v-model="skuInfo.skuDesc" rows="4" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(attr, index) in attrList" :key="attr.id" :md="12" :sm="12" :xs="24" :lg="8">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" @change="clearAttrRules">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id"
                :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                :label="attrValue.valueName" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row :gutter="20">
        <el-col v-for="(saleAttr, index) in spuSaleAttrList" :key="saleAttr.id" :md="12" :sm="12" :lg="8">
          <el-form-item :label="saleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" @change="clearSaleAttrRules">
              <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`"
                :label="saleAttrValue.saleAttrValueName" :key="saleAttrValue.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table border :data="spuImageList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="图片" align="center">
          <template v-slot="{ row, $index }">
            <el-image :src="row.imgUrl" :alt="row.imgName" style="width:100px;height:100px" />
          </template>
        </el-table-column>
        <el-table-column label="图片名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="primary" v-if="row.isDefault === '0'" @click="setDefault(row)">设为默认项</el-button>
            <el-button type="success" v-else disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitForm(skuFormRef)">保存</el-button>
      <el-button @click="emits('changeScene', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: 'SkuForm'
}
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqGetAttrListData } from '@/api/product/attr'
import { useCategoryListStore } from '@/stores/categoryList'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reqSaveSkuInfo } from '@/api/product/sku'
const categoryStore = useCategoryListStore()
const props = defineProps(['currentSpuInfo'])
const emits = defineEmits(['changeScene'])
const num = ref(0)
const weight = ref(0)
// 定义三个变量来存储响应回来的数据
// 图片列表
const spuImageList = ref([])
// spu基础属性列表
const spuSaleAttrList = ref([])
// 平台属性列表
const attrList = ref([])

const skuFormRef = ref<FormInstance>()
interface User {
  date: string
  name: string
  address: string
}

const skuInfo = reactive({
  // spu名称
  skuName: '',
  // 价格
  price: 0,
  // 重量
  weight: 0,
  // 描述
  skuDesc: '',
  // 默认图片
  skuDefaultImg: '',
  // 平台属性
  skuAttrValueList: [],
  // 图片列表
  skuImageList: [],
  // 销售属性列表
  skuSaleAttrValueList: []
})

const skuImageListValidate = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback('请至少选择一张图片...')
    return
  }
  if (!value.find(item => item.isDefault === '1')) {
    callback('请选择默认图片...')
    return
  }
  callback() // 什么参数都不写，表示放行
}
const skuAttrValueListValidate = (rule: any, value: any, callback: any) => {
  // console.log(rule,value)
  if (!value.length) {
    return callback('请选择一个平台属性')
  }
  callback()
}
const skuSaleAttrValueListValidate = (rule: any, value: any, callback: any) => {
  // console.log(rule,value)
  if (!value.length) {
    return callback('请选择一个平台属性')
  }
  callback()
}

const skuRules = reactive<FormRules>({
  skuName: [
    { required: true, message: '请输入Sku名称', trigger: 'blur' },
    { min: 1, max: 10, message: 'Sku名称在1---10之间', trigger: 'blur' }
  ],
  price: [{ required: true, message: '请输入Sku价格', trigger: 'change' }],
  weight: [{ required: true, message: '请输入Sku重量', trigger: 'change' }],
  skuDesc: [{ required: true, message: '请输入Sku描述', trigger: 'blur' }],
  skuImageList: [{ required: true, validator: skuImageListValidate, type: 'array', trigger: 'change' }],
  skuAttrValueList: [{ required: true, validator: skuAttrValueListValidate, trigger: 'change' }],
  skuSaleAttrValueList: [{ required: true, validator: skuSaleAttrValueListValidate, trigger: 'change' }]
})

// 1. 组件挂载完毕就要发送请求
onMounted(async () => {
  const spuId = props.currentSpuInfo.id
  const [resSpuImageList, resSpuSaleAttrList, resAttrList] = await Promise.allSettled([reqGetSpuImageList(spuId), reqGetSpuSaleAttrList(spuId), reqGetAttrListData({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number
  })])


  // 赋值
  if (resSpuImageList?.status === 'fulfilled') {
    spuImageList.value = resSpuImageList.value.map(item => {
      return {
        ...item,
        isDefault: '0'
      }
    })
  }
  if (resSpuSaleAttrList.status === 'fulfilled') {
    spuSaleAttrList.value = resSpuSaleAttrList.value
  }
  if (resAttrList.status === 'fulfilled') {
    attrList.value = resAttrList.value
  }
})

// 2. 单击按钮 设置为默认图片
const setDefault = (row) => {
  // 先将所有的设置为0
  spuImageList.value.forEach(item => {
    item.isDefault = '0'
  })
  // 自己的设置为1
  row.isDefault = '1'

  // 保存一下默认图片的地址
  skuInfo.skuDefaultImg = row.imgUrl
}

// 3. 当选择图片的时候
const handleSelectionChange = (val) => {
  console.log(val)
  skuInfo.skuImageList = val
}

// 4. 添加Sku时的校验
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // console.log('submit!')
      skuInfo.skuAttrValueList = skuInfo.skuAttrValueList.filter(Boolean).map(item => {
        const [attrId, attrName, valueId, valueName] = item.split(':')
        return {
          attrId, attrName, valueId, valueName
        }
      })
      skuInfo.skuSaleAttrValueList = skuInfo.skuSaleAttrValueList.filter(Boolean).map(item => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
        return {
          saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName
        }
      })
      skuInfo.spuId = props.currentSpuInfo.spuId
      skuInfo.category3Id = categoryStore.category3Id
      await reqSaveSkuInfo(skuInfo)
      ElMessage.success('添加Sku成功...')
      // 跳转到列表页
      emits('changeScene', 1)
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 5. 清空平台属性的校验规则
const clearAttrRules = () => {
  skuFormRef.value?.clearValidate(['skuAttrValueList'])
}

// 6. 清空销售属性的校验规则
const clearSaleAttrRules = () => {
  console.log('事件触发...aaaa')
  skuFormRef.value?.clearValidate(['skuSaleAttrValueList'])
}
</script>

<style>
</style>